package com.ftg.learn.chapter04.linetable;

import java.util.LinkedList;

/**
 * @author 布衣
 */
public class DoubleTwoList {

    // 状态
    // 行为
    // 内部类
    private class NodeTwo {
        NodeTwo prev;
        int val;
        NodeTwo next;

        public NodeTwo(int val) {
            this.val = val;
        }

        public NodeTwo() {
        }

        public NodeTwo(NodeTwo prev, int val, NodeTwo next) {
            this.val = val;
            this.prev = prev;
            this.next = next;
        }

    }

    private NodeTwo head;
    private NodeTwo tail;
    private NodeTwo middle;
    private int size;

    // 自我完成头插入
    public void add(int val) {
        size++;
        if (head == null) {
            head = new NodeTwo(val);
            tail = head;
            middle = tail;
            return;
        }
        tail.next = new NodeTwo(tail, val, null);
        tail = tail.next;
        middle = (size % 2 == 0) ? middle.next : middle;
    }

    /**
     * 遍历 获取元素 求单一元素
     *
     * @param index 索引
     * @return int
     */
    public int get(int index) {
        return getNodeByIndex(index).val;
    }

    /**
     * 根据索引获取节点
     *
     * @param index 索引
     * @return 节点
     */
    public NodeTwo getNodeByIndex(int index) {
        //临界
        if (index < 0 || index >= size) {
            return null;
        }
        if (index == 0) {
            return head;
        }
        if (index == size - 1) {
            return tail;
        }
        //奇 偶
        int middleVal = size / 2;
        if (index < middleVal) {
            NodeTwo temp;
            if (index - (middleVal - index) > 0) {
                temp = middle;
                while (temp != null) {
                    temp = temp.prev;
                    if (index == --middleVal) {
                        return temp;
                    }
                }
            }
        } else if (index == middleVal) {
            return middle;
        } else {

        }
        return null;
    }

    public static void main(String[] args) {
        DoubleTwoList doubleTwoList = new DoubleTwoList();
        doubleTwoList.add(1);
        doubleTwoList.add(2);
        doubleTwoList.add(3);
        doubleTwoList.add(4);
        doubleTwoList.add(5);
        doubleTwoList.add(6);
        doubleTwoList.add(7);
        doubleTwoList.add(8);
        doubleTwoList.add(9);

        System.out.println(doubleTwoList.getNodeByIndex(5).val);

//        for (int i = 0; i < doubleTwoList.size; i++) {
//            System.out.println(doubleTwoList.get(i));
//        }
    }

    // 四道题
    // 中等 （2道）


}
